<template>
  <div>
    <!-- 商品介绍 -->
    <el-card class="box-card">
      <div>
        <!-- 这里将el-descriptions和el-descriptions-item替换为div -->
        <h2>{{ pageTitle }}</h2>
        <div class="gDiv">
          <el-form ref="form" :model="form" :rules="rules" label-width="92px" :disabled="isApproval">
            <el-form-item label="商品编号" prop="goodsSn">
              <el-input v-model="form.goodsSn" style="width: 1478px;" />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" style="width: 1478px;" />
            </el-form-item>
            <el-form-item label="专柜价格" prop="counterPrice">
              <el-input v-model="form.counterPrice" style="width: 1410px;" />
              <span class="yuan">元</span>
            </el-form-item>
            <el-form-item label="当前价格" prop="retailPrice">
              <el-input v-model="form.retailPrice" style="width: 1410px;" />
              <span class="yuan">元</span>
            </el-form-item>

            <el-form-item label="佣金设置">
              <template>
                <el-radio v-model="form.resource" :label="0" @change="hanleBrosChange">无佣金</el-radio>
                <el-radio v-model="form.resource" :label="1" @change="handleBroChange">自定义</el-radio>
              </template>
            </el-form-item>

            <el-form-item label="佣金" v-if="brokerPc">
              <el-input v-model="form.brokeragePrice" style="width: 1478px;" />
            </el-form-item>

            <el-form-item label="是否新品">
              <template>
                <el-radio v-model="form.isNew" :label="1">新品</el-radio>
                <el-radio v-model="form.isNew" :label="2">非新品</el-radio>
              </template>
            </el-form-item>

            <el-form-item label="是否热卖" prop="isHot">
              <template>
                <el-radio v-model="form.isHot" :label="1">普通</el-radio>
                <el-radio v-model="form.isHot" :label="2">热卖</el-radio>
              </template>
            </el-form-item>

            <el-form-item label="是否在售" prop="isOnSale">
              <template>
                <el-radio v-model="form.isOnSale" :label="1">在售</el-radio>
                <el-radio v-model="form.isOnSale" :label="2">未售</el-radio>
              </template>
            </el-form-item>

            <el-form-item label="商品图片" prop="picUrl">
              <el-upload v-model="form.picUrl" :file-list="fileList" :limit="1"  :before-upload="(file) => handleImageChange(file, 'picUrl')"
                :show-file-list="false" class="avatar-uploader" action="#">
                <!-- 自定义上传按钮或图片预览 -->
                <img v-if="form.picUrl" :src="form.picUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>


            <el-form-item label="宣传画廊" prop="gallery">
              <el-upload
                v-model="form.gallery"
                :multiple="true"
                :limit="5"
                :before-upload="(file) => handleImageChange(file, 'gallery')"
                class="avatar-uploader"
                action="#"
              >
                <div class="upload-preview" v-if="form.gallery && form.gallery.length > 0">
                  <img v-for="(url, index) in form.gallery" :key="index" :src="url" class="avatar" />
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="form.unit" style="width: 1478px;" />
            </el-form-item>

            <el-form-item label="关键字">
              <div class="keyword-display">
                <span v-for="(item, index) in form.keywords" :key="index" class="keyword-item">
                  {{item}}
                  <i class="el-icon-close" @click="removeKeyword(index)"></i>
                </span>
              </div>
              <el-input v-model="inputKeyword" placeholder="请输入内容" class="keyword-input" v-if="showInput"
                @blur="addContentToPage" @keyup.enter.native="addContentToPage"></el-input>
              <el-button type="primary" v-show="!isAdding" @click="showInput = true; isAdding = true"> + 增加</el-button>
            </el-form-item>

            <el-form-item label="所属分类" style="width: 298px;" prop="category">
              <el-cascader v-model="form.category" :options="categoryOptions" :props="cascaderProps"
                expand-trigger="hover" placeholder="请选择分类" clearable style="width: 100%" />
            </el-form-item>

            <el-form-item label="所属品牌商" prop="brand">
              <el-select v-model="form.brand" @change="handleGoodsIdChange">
                <el-option v-for="goods in BrandList" :key="goods.id" :value="goods.id"
                  :label="goods.name">{{goods.name}}</el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="商品简介" prop="brief">
              <el-input v-model="form.brief" style="width: 1478px;" />
            </el-form-item>

            <el-form-item label="信息内容">
              <editor v-model="form.detail" :min-height="190" class="editor-content"
                style="width: 1478px; height: 240px;" :disabled="isApproval" />
            </el-form-item>

            <!-- <el-form-item>
              <el-button>取消</el-button>
              <el-button type="primary" @click="onSubmit">上架</el-button>
            </el-form-item> -->
          </el-form>
        </div>
      </div>
    </el-card>
    <!-- 商品规格 -->
    <el-card class="sbox-card">
      <div>
        <!-- 这里将el-descriptions和el-descriptions-item替换为div -->
        <h2>商品规格</h2>
        <div class="gDiv">
          <div class="BtnDiv">
            <el-button-group class="spec-btn-group" v-show="updIsTF"> <!-- 添加自定义类 -->
              <!-- 默认标准规格按钮 -->
              <el-button :class="{ 'active-btn': currentBtn === 'default' }" @click="handleDefaultClick()">
                默认标准规格
              </el-button>
              <!-- 多规格支持按钮 -->
              <el-button :class="{ 'active-btn': currentBtn ==='multiple' }" @click="handleMultipleClick()">
                多规格支持
              </el-button>
            </el-button-group>
            <!-- 根据选中状态显示添加按钮 -->
            <el-button style="margin-left: 600px;" v-if="currentBtn ==='multiple' || aa && !isApproval" type="primary"
              icon="el-icon-plus" plain @click="dialogVisible = true">
              添加
            </el-button>

            <!-- 添加多规格 -->
            <el-dialog title="设置规格" :visible.sync="dialogVisible" width="30%">
              <el-form label-position="left" label-width="80px" :model="formLabelAlign">
                <el-form-item label="规格名">
                  <el-input v-model="formLabelAlign.specification"></el-input>
                </el-form-item>
                <el-form-item label="规格值">
                  <el-input v-model="formLabelAlign.value"></el-input>
                </el-form-item>
                <el-form-item label="规格图片" prop="picUrl">
                  <el-upload v-model="formLabelAlign.picUrl" :limit="1"  :before-upload="(file) => handleImageChange(file, 'guiGeUrl')"
                    :show-file-list="false" class="avatar-uploader" action="#">
                    <!-- 自定义上传按钮或图片预览 -->
                    <img v-if="formLabelAlign.picUrl" :src="formLabelAlign.picUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addSpecification();dialogVisible = false">确 定</el-button>
              </span>
            </el-dialog>

          </div>
          <el-table :data="tableData" style="width: 100%;" max-height="400">
            <el-table-column prop="specification" label="规格名">
            </el-table-column>
            <el-table-column prop="value" label="规格值">
            </el-table-column>
            <el-table-column label="规格图片">
              <template slot-scope="scope">
                <div v-if="scope.row.picUrl" class="spec-image-container">
                  <img :src="scope.row.picUrl" alt="规格图片" class="spec-image" @error="handleImageError(scope.$index)">
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="currentBtn ==='multiple' || aa && !isApproval">
              <template slot-scope="scope">
                <el-button type="danger" @click="handleDelete(scope.row)"
                  v-hasPermi="['good:commodity:goods:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 商品库存 -->
    <el-card class="sbox-card">
      <div>
        <!-- 这里将el-descriptions和el-descriptions-item替换为div -->
        <h2>商品库存</h2>
        <div class="gDiv">
          <el-table :data="goodsKc" style="width: 100%" max-height="400">
            <el-table-column prop="specifications" label="商品规格">
            </el-table-column>
            <el-table-column prop="price" label="货品售价">
            </el-table-column>
            <el-table-column prop="number" label="货品数量">
            </el-table-column>
            <el-table-column prop="url" label="货品图片">
              <template slot-scope="scope">
                <div v-if="scope.row.url" class="spec-image-container">
                  <img :src="scope.row.url" alt="规格图片" class="spec-image" @error="handleImageError(scope.$index)">
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="!isApproval">
              <template slot-scope="scope">
                <el-button type="text" @click="goodsNum = true, hand(scope.row)"
                  v-hasPermi="['good:commodity:goods:remove']">设置</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-dialog title="设置货品" :visible.sync="goodsNum" width="30%">
          <el-form label-position="right" label-width="120px" :model="goodsK">
            <el-form-item label="货品规格列">
              <el-input v-model="goodsK.specifications" readonly></el-input>
            </el-form-item>
            <el-form-item label="货品售价">
              <el-input v-model="goodsK.price"></el-input>
            </el-form-item>
            <el-form-item label="货品数量">
              <el-input v-model="goodsK.number"></el-input>
            </el-form-item>
            <el-form-item label="货品图片">
              <el-upload v-model="goodsK.url" :limit="1"  :before-upload="(file) => handleImageChange(file, 'url')"
                :show-file-list="false" class="avatar-uploader" action="#">
                <!-- 自定义上传按钮或图片预览 -->
                <img v-if="goodsK.url" :src="goodsK.url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="goodsNum = false">取 消</el-button>
            <el-button type="primary" @click="goodsNum = false;sellingPrice()">确 定</el-button>
          </span>
        </el-dialog>

      </div>
    </el-card>

    <!-- 商品参数 -->
    <el-card class="sbox-card">
      <div>
        <!-- 这里将el-descriptions和el-descriptions-item替换为div -->
        <h2>商品参数</h2>
        <el-button style="margin-left: 20px;" v-show="!isApproval" type="primary" icon="el-icon-plus" plain
          @click="goodsIsT = true">
          添加
        </el-button>
        <!-- 设置商品参数 -->
        <el-dialog title="设置商品参数" :visible.sync="goodsIsT" width="30%">
          <el-form label-position="left" label-width="120px" :model="goodsCan">
            <el-form-item label="商品参数名称">
              <el-input v-model="goodsCan.attribute"></el-input>
            </el-form-item>
            <el-form-item label="商品参数值">
              <el-input v-model="goodsCan.value"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="goodsIsT = false">取 消</el-button>
            <el-button type="primary" @click="goodsIsT = false;addGoodsAttribute()">确 定</el-button>
          </span>
        </el-dialog>

        <div class="gDiv">
          <el-table :data="goodsInventory" style="width: 100%" max-height="540">
            <el-table-column prop="attribute" label="商品参数名称">
            </el-table-column>
            <el-table-column prop="value" label="商品参数值">
            </el-table-column>
            <el-table-column label="操作" v-if="!isApproval">
              <template slot-scope="scope">
                <el-button type="text" @click="handleDelete1(scope.row)"
                  v-hasPermi="['good:commodity:goods:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
    <div style="margin-left: 20px;margin-bottom: 20px;">
      <el-button @click="back" v-show="!updIsTF">取消</el-button>
      <el-button type="primary" @click="onSubmit" v-show="updIsTF">上架</el-button>
      <el-button type="primary" @click="onUpdate" v-show="!updIsTF && !isApproval">更新商品</el-button>
      <el-button type="primary" @click="shen = true, goodsShen.approveStatus = 2" v-show="isApproval">审批不通过</el-button>
      <el-button type="primary" @click="shen = true, goodsShen.approveStatus = 1" v-show="isApproval">审批通过</el-button>

      <el-dialog title="审批" :visible.sync="shen" width="30%">
        <el-form label-position="right" label-width="120px" :model="goodsShen">
          <el-form-item label="审批内容">
            <el-input v-model="goodsShen.approveMsg"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="shen = false">取 消</el-button>
          <el-button type="primary" @click="shen = false; shenpi()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>

</template>

<script>
  import {
    getParentCategorie
  } from "@/api/emporium/category";
  import {
    listBrand
  } from "@/api/emporium/brand";
  import {
    addGoods,
    selGoods,
    updateGoods
  } from "@/api/good/commodity/goods";
  import {
    addImage
  } from "@/api/oss/upload";
  import OSS from 'ali-oss';
  export default {
    data() {
      return {
        ossClient: null,
        shen: false,
        goodsNum: false,
        currentBtn: "default",
        brokerPc: false,
        dialogVisible: false,
        goodsIsT: false,
        showInput: false,
        inputKeyword: '',
        isAdding: false,
        updIsTF: true,
        aa: false,
        dtsGoodsAttribute1: [],
        dtsGoodsProduct1: [],
        dtsGoodsSpecification1: [],
        // 商品介绍
        form: {
          goodsSn: null,
          name: "",
          counterPrice: null,
          retailPrice: null,
          brokerageType: null,
          brokeragePrice: null,
          picUrl: null,
          gallery: [],
          resource: 0,
          isNew: null,
          isHot: null,
          brand: null,
          isOnSale: "",
          unit: "",
          keywords: [],
          category: [],
          brief: "",
          detail: "",
          commpany: "",
        },
        goodsShen: {
          approveStatus: 2,
          approveMsg: "",
          id: this.$route.query.id,
        },
        goods: {

        },
        // 品牌
        BrandList: [],
        // 标准规格
        tableData: [{
          specification: "规格",
          value: "标准",
          picUrl: "",
        }, ],
        // 设置规格
        formLabelAlign: {
          specification: "",
          value: "",
          picUrl: "",
        },
        queryParams: {
          id: null,
          pid: null,
        },
        queryParam: {
          id: null,
        },
        rules: {
          goodsSn: [{
            required: true,
            message: "商品编号不能为空",
            trigger: "blur"
          }, ],
          name: [{
            required: true,
            message: "商品名称不能为空",
            trigger: "blur"
          }, ],
          retailPrice: [{
              required: true,
              message: "当前价格不能为空",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                if (isNaN(Number(value))) {
                  callback(new Error('当前价格必须为数字'));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ],
          counterPrice: [{
            validator: (rule, value, callback) => {
              if (isNaN(Number(value))) {
                callback(new Error('当前价格必须为数字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }],
          category: [{
            required: true,
            message: "请选择分类",
            trigger: "blur"
          }],
          brand: [{
            required: true,
            message: "请选择品牌",
            trigger: "blur"
          }],
        },
        // 商品类目
        categoryOptions: [{
            value: "fashion",
            label: "女装/男装",
            children: [{
              value: "digital",
              label: "数码产品",
              children: [{
                value: "phone",
                label: "手机配件"
              }],
            }, ],
          },
          {
            value: "kids",
            label: "童装/母婴",
          },
          {
            value: "digital家电",
            label: "数码家电",
          },
          {
            value: "beauty",
            label: "美妆日化",
          },
          {
            value: "office",
            label: "办公文教",
          },
        ],
        cascaderProps: {
          value: "id",
          label: "name",
          children: "categoryList",
        },
        goodsKc: [],
        goodsK: {
          specifications: '', // 货品规格列
          price: 0, // 货品售价
          number: 0, // 货品数量
          url: '' // 货品图片
        },
        // 商品参数
        goodsInventory: [],
        // 商品参数
        goodsCan: {
          attribute: "",
          value: "",
        },
        url: '',
        num: -1,
        originalSpecs: [{
            guige: "颜色",
            guigezhi: "黄色"
          },
          {
            guige: "颜色",
            guigezhi: "绿色"
          },
          {
            guige: "尺寸",
            guigezhi: "1cm"
          },
          {
            guige: "尺寸",
            guigezhi: "2cm"
          },
          {
            guige: "款式",
            guigezhi: "毛衣"
          },
        ],
        mergedSpecs: [],
        specOrder: [], // 记录规格名首次出现的顺序
        isApproval: false, // 是否是审批页面
        uploadUrl: '',
        previewUrls: [],
        fileList: [], // 初始化为空数组
      };
    },
    created() {
      this.getList();
      this.initOSSClient();
      if (this.$route.query.id != undefined && this.$route.query.id > 0) {
        this.updIsTF = false;
        this.aa = true;
        this.selGood(this.$route.query.id);
      }
      this.brokerPc = this.form.resource === 2;

      this.handleDefaultClick();
      this.hand();
      this.goodsKc.push();
    },
    computed: {
      pageTitle() {
        // 如果 meta.title 存在且不为空字符串，则使用它；否则显示 "商品上架"
        return this.$route.meta.title || '商品上架';
      }
    },
    methods: {
      onSubmit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let goods = {
              ...this.form,
              dtsGoodsProduct: this.goodsKc,
              dtsGoodsAttribute: this.goodsInventory,
              dtsGoodsSpecification: this.tableData
            };
            goods.gallery = goods.gallery.toString();
            goods.keywords = goods.keywords.toString();
            goods.category = parseInt(goods.category[1]);
            goods.brandId = goods.brand;
            goods.categoryId = goods.category;
            goods.brokerageType = this.form.resource;
            addGoods(goods).then(() => {
              this.$message.success('商品上架成功');
              this.$router.push({
                path: '/goods/select',
              })
            }).catch(() => {
              this.$message.error('商品上架失败');
            });
          } else {
            this.$message.error('表单验证不通过，请检查输入内容');
            return false;
          }
        });
      },
      // 处理回车事件
      handleEnter() {
        this.addKeyword(); // 调用添加关键字的核心逻辑
        this.showInput = false; // 隐藏输入框
        this.isAdding = false; // 重置添加状态
        this.inputKeyword = ''; // 清空输入框
      },
      selGood(id) {
        selGoods(id).then(response => {
          this.goods = response.data;
          console.log(JSON.stringify(this.goods, null, 2));
          this.dtsGoodsAttribute1 = this.goods.dtsGoodsAttribute.slice();
          this.dtsGoodsProduct1 = this.goods.dtsGoodsProduct.slice();
          this.dtsGoodsSpecification1 = this.goods.dtsGoodsSpecification.slice();
          this.goodsInventory = this.goods.dtsGoodsAttribute.slice();
          this.tableData = this.goods.dtsGoodsSpecification.slice();
          this.form.goodsSn = this.goods.goodsSn;
          this.form.name = this.goods.name;
          this.form.counterPrice = this.goods.counterPrice;
          this.form.retailPrice = this.goods.retailPrice;
          this.form.resource = this.goods.brokerageType;
          this.form.brokeragePrice = this.goods.brokeragePrice;
          this.form.isNew = this.goods.isNew;
          this.form.isHot = this.goods.isHot;
          this.form.isOnSale = this.goods.isOnSale;
          this.form.picUrl = this.goods.picUrl;
          this.form.gallery = JSON.parse(this.goods.gallery);
          this.form.unit = this.goods.unit;
          this.form.keywords = this.goods.keywords.split(',');
          this.form.category = this.goods.categoryId;
          this.form.brand = Number(this.goods.brandId);
          this.form.brief = this.goods.brief;
          this.form.detail = this.goods.detail;
          // 按规则排序：先按首次出现顺序，再按插入顺序
          this.sortTableData();
          // 生成规格组合
          this.guige();
          this.goods.dtsGoodsProduct = this.goods.dtsGoodsProduct.map(item => ({
            ...item,
            specifications: JSON.parse(item.specifications).join(',')
          }));
          this.goodsKc.forEach(item => {
            this.goods.dtsGoodsProduct.forEach(product => {
              if (item.specifications === product.specifications) {
                item.price = product.price;
                item.number = product.number;
                item.url = product.url;
                item.id = product.id;
              }
            });
          });
        })
        this.isApproval = this.$route.meta.title === '商品审批';
        console.log(JSON.stringify(this.form, null, 2));
      },
      // 修改商品规格
      onUpdate() {
        // console.log(JSON.stringify(this.goods, null, 2));
        console.log(JSON.stringify(this.tableData, null, 2));
        // console.log(JSON.stringify(this.goodsInventory, null, 2));
        // console.log(JSON.stringify(this.dtsGoodsAttribute1, null, 2));
        // console.log(JSON.stringify(this.goodsKc, null, 2));
        this.$refs.form.validate((valid) => {
          if (valid) {
            let goods = {
              ...this.form,
              dtsGoodsProduct: this.goodsKc,
              dtsGoodsAttribute: this.goodsInventory,
              dtsGoodsSpecification: this.tableData
            };
            goods.gallery = goods.gallery.toString();
            goods.keywords = goods.keywords.toString();
            goods.category = parseInt(goods.category[1]);
            goods.brandId = goods.brand;
            goods.categoryId = goods.category;
            goods.brokerageType = this.form.resource;
            goods.id = this.goods.id;
            console.log(JSON.stringify(this.form, null, 2));
            console.log(JSON.stringify(goods, null, 2));
            updateGoods(goods).then(() => {
              this.$message.success('商品修改成功');
              this.back();
            }).catch(() => {
              this.$message.error('商品上架失败');
            });
          } else {
            this.$message.error('表单验证不通过，请检查输入内容');
            return false;
          }
        });
      },
      // 规格
      guige() {
        this.mergedSpecs = [];
        // 用于按规格名称对原始数据进行分组的对象
        const groupedSpecs = {};
        // 遍历原始规格数据数组
        this.tableData.forEach(item => {
          // 如果 groupedSpecs 对象中不存在当前规格名称的属性
          if (!groupedSpecs[item.specification]) {
            // 则为该规格名称创建一个空数组
            groupedSpecs[item.specification] = [];
          }
          // 将当前规格值添加到对应的规格名称数组中
          groupedSpecs[item.specification].push(item.value);
        });

        // 获取所有规格名称的数组
        const specsKeys = Object.keys(groupedSpecs);
        // 递归函数，用于生成所有可能的规格组合
        const generateCombinations = (index, currentCombination) => {
          // 当 index 等于规格名称数组的长度时，说明已经生成了一种完整的组合
          if (index === specsKeys.length) {
            // 创建一个新的组合对象，包含规格组合、售价、数量和图片字段
            const combination = {
              specifications: currentCombination.join(','),
              // 示例售价，可根据实际情况修改
              price: 0,
              // 示例数量，可根据实际情况修改
              number: 0,
              // 示例图片链接，可根据实际情况修改
              url: '',
              id: 0,
            };
            this.mergedSpecs.push(combination);
            return;
          }
          // 获取当前规格名称对应的所有规格值数组
          const currentSpecValues = groupedSpecs[specsKeys[index]];
          // 遍历当前规格值数组
          currentSpecValues.forEach(value => {
            // 递归调用 generateCombinations 函数，处理下一个规格名称
            generateCombinations(index + 1, [...currentCombination, value]);
          });
        };

        // 从第一个规格名称开始调用递归函数，初始组合为空数组
        generateCombinations(0, []);
        this.goodsKc = this.mergedSpecs;
      },
      // 查询类目
      getList() {
        getParentCategorie(this.queryParams).then((response) => {
          this.categoryOptions = response;
        });

        listBrand(this.queryParam).then((response) => {
          this.BrandList = response.rows;
        });
      },
      shenpi() { // 进行审批
        console.log(JSON.stringify(this.goodsShen, null, 2));
        updateGoods(this.goodsShen).then((response) => {
          if (this.goodsShen.approveStatus == 1 && response.data > 0) {
            console.log("审批通过");
          } else if (this.goodsShen.approveStatus == 2 && response.data > 0) {
            console.log("审批不通过");
          }
          this.$message({
            message: '审批成功',
            type: 'success'
          });
          this.back();
        })
      },
      back() {
        this.$router.back();
      },
      handleBroChange() {
        this.brokerPc = true;
        this.form.brokeragePrice = '';
      },
      hanleBrosChange() {
        this.brokerPc = false;
      },
      handleDefaultClick() {
        this.goodsKc = [];
        this.currentBtn = "default";
        this.tableData = [{
          specification: "规格",
          value: "标准",
          picUrl: ""
        }];
        this.goodsKc.push({
          specifications: this.tableData[0].value,
          price: 0,
          number: 0,
          url: '',
        });
        console.log(this.form.picUrl);
        if (this.goods != null && this.goods != {}) {
          this.goodsKc.forEach(item => {
            this.goods.dtsGoodsProduct.forEach(product => {
              if (item.specifications === product.specifications) {
                item.price = product.price;
                item.number = product.number;
                item.url = product.url;
                item.id = product.id;
              }
            });
          });
        }
      },
      handleMultipleClick() {
        this.goodsKc = [];
        this.currentBtn = "multiple";
        this.tableData = [];
      },
      addSpecification() {
        // 复制表单数据
        const newItem = {
          ...this.formLabelAlign
        };

        // 记录规格名首次出现的顺序
        if (!this.specOrder.includes(newItem.specification)) {
          this.specOrder.push(newItem.specification);
        }

        // 添加到表格数据
        this.tableData.push(newItem);

        // 按规则排序：先按首次出现顺序，再按插入顺序
        this.sortTableData();

        // 生成规格组合
        this.guige();

        if (this.$route.meta.title === '商品编辑') {
          this.goodsKc.forEach(item => {
            this.goods.dtsGoodsProduct.forEach(product => {
              if (item.specifications === product.specifications) {
                item.price = product.price;
                item.number = product.number;
                item.url = product.url;
                item.id = product.id;
              }
            });
          });
        }

        this.tableData.forEach(item => {
          this.dtsGoodsSpecification1.forEach(product => {
            if (item.specification === product.specification && item.value === product.value) {
              item.id = product.id;
            }
          })
        })

        // 清空表单
        this.formLabelAlign = {
          specification: "",
          value: "",
          picUrl: ""
        };
      },
      sortTableData() {
        // 动态提取当前所有规格名的唯一顺序（按首次出现位置）
        const specOrder = [...new Map(
          this.tableData.map(item => [item.specification, item.specification])
        ).values()];

        // 按动态提取的规格名顺序和插入顺序排序
        this.tableData.sort((a, b) => {
          const indexA = specOrder.indexOf(a.specification);
          const indexB = specOrder.indexOf(b.specification);

          // 先按规格名顺序排序
          if (indexA !== indexB) {
            return indexA - indexB;
          }

          // 规格名相同，按原始插入顺序（数组索引）排序
          return this.tableData.indexOf(a) - this.tableData.indexOf(b);
        });
      },
      addGoodsAttribute() {
        this.goodsInventory.push({
          ...this.goodsCan
        });
        this.goodsCan = {
          attribute: "",
          value: "",
        };

        this.goodsInventory.forEach(item => {
          this.dtsGoodsAttribute1.forEach(attr => {
            if (item.attribute === attr.attribute) {
              item.id = attr.id;
            }
          })
        })
      },

      handleAvatarSuccess(response, file, fileList) {
        // 处理上传成功的逻辑
      },
      beforeAvatarUpload(file) {
        // 处理上传前的逻辑
        return true;
      },
      handleDelete(row) {
        // 从规格表格中删除
        const index = this.tableData.indexOf(row);
        if (index > -1) {
          this.tableData.splice(index, 1);
        }
        // 更新商品库存中的规格信息
        this.guige();

        if (this.$route.meta.title === '商品编辑') {
          this.goodsKc.forEach(item => {
            this.goods.dtsGoodsProduct.forEach(product => {
              if (item.specifications === product.specifications) {
                item.price = product.price;
                item.number = product.number;
                item.url = product.url;
                item.id = product.id;
              }
            });
          });
        }
        if (this.tableData.length == 0) {
          this.goodsKc = [];
        }
      },
      handleDelete1(row) {
        // 从参数表格中删除
        const index = this.goodsInventory.indexOf(row);
        if (index > -1) {
          this.goodsInventory.splice(index, 1);
        }
      },
      handleGoodsIdChange(value) {
        // 处理品牌选择变化的逻辑
        this.form.brand = value; // 确保赋值正确

        // 查找并设置品牌所属公司
        const selectedBrand = this.BrandList.find(item => item.id === value);
        if (selectedBrand) {
          this.form.commpany = selectedBrand.commpany;
        }
        console.log('Company:', this.form.commpany);
        console.log('Company:', this.form.brand);
        console.log('Company:', this.goods.brandId);
      },
      // 新增关键字
      addContentToPage() {
        if (this.inputKeyword.trim() !== '') {
          this.form.keywords.push(this.inputKeyword.trim());
          this.showInput = false;
          this.inputKeyword = '';
          this.isAdding = false;
        }
        console.log(JSON.stringify(this.form.keywords, null, 2));
      },
      // 删除关键字
      removeKeyword(index) {
        this.form.keywords.splice(index, 1);
      },
      hand(row) {
        const index = this.goodsKc.indexOf(row);
        this.num = index;
        console.log(index);
        this.goodsK = {
          ...row
        };
      },
      sellingPrice() {
        this.goodsKc[this.num].number = this.goodsK.number;
        this.goodsKc[this.num].price = this.goodsK.price;
        this.goodsKc[this.num].url = this.goodsK.url;
      },

      async handleImageChange(file, extraParam) {
        if (file) {
          console.log(JSON.stringify(file, null, 2));
          const isImage = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
          if (!isImage) {
            this.$message.error('只能上传JPG/PNG格式的图片!');
            return false;
          }

          const isLt3M = file.size / 1024 / 1024 < 3;
          if (!isLt3M) {
            this.$message.error('图片大小不能超过3MB!');
            return false;
          }

          try {
            // 生成更简单的文件名
            const fileName = `product-images/${Date.now()}-${file.name}`;

            console.log('开始上传文件到OSS:', fileName);
            console.log('开始OSS:', file);

            // 使用put方法代替multipartUpload
            const result = await this.ossClient.put(fileName, file);
            console.log('OSS上传结果:', result);

            // 生成可直接访问的URL
            const imageUrl = result.url;
            console.log('生成的文件URL:', imageUrl);

            switch (extraParam) {
                case "picUrl":
                    this.form.picUrl = imageUrl;
                    break;
                case "gallery":
                    console.log("其他情况处理");
                    break;
                case "guiGeUrl":
                    this.formLabelAlign.picUrl = imageUrl;
                    break;
                case "url":
                    this.goodsK.url = imageUrl;
                    break;
                default:
                    console.log("未匹配到任何情况");
            }

            // 更新fileList和form.image
            this.fileList.push({
              name: file.name,
              url: imageUrl
            });
            // 确保form.image是对象数组
            this.form.image = this.fileList.map(item => ({
              name: item.name,
              url: item.url
            }));

            console.log('当前fileList:', this.fileList);
            console.log('当前form.image:', this.form.image);

            this.$message.success('图片上传成功');
            return false;
          } catch (error) {
            console.error('上传失败:', error);
            this.$message.error(`上传失败: ${error.message}`);
            return false;
          }
        }
      },
      // 初始化OSS客户端
      initOSSClient() {
        try {
          this.ossClient = new OSS({
            region: 'oss-cn-shenzhen',
            accessKeyId: 'LTAI5tJDNLAHLvTNUxffAYo5',
            accessKeySecret: 'pvXyZSJRoiTEK3HsKms4sk1tzT69Ky',
            bucket: 'jhx-img',
            secure: true,
            // 添加以下配置
            endpoint: 'https://oss-cn-shenzhen.aliyuncs.com',
            cname: false
          });
          console.log('OSS客户端初始化成功');
        } catch (error) {
          console.error('OSS初始化失败:', error);
          this.$message.error('OSS服务初始化失败');
        }
      },
      // 在上传前处理文件
      beforeUpload(file) {
        const isImage = file.type.startsWith('image/');
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isImage) {
          this.$message.error('上传文件只能是图片!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      },
    },
  };
</script>

<style scoped>
  .gDiv {
    margin-left: 20px;
  }

  .yuan {
    color: #F5A099;
    margin-left: -3px;
    border: solid #DCDFE6 1px;
    border-radius: 0px 3px 3px 0px;
    background-color: #F5F7FA;
    padding-left: 27px;
    padding-right: 28px;
    padding-top: 9px;
    padding-bottom: 9px;
  }

  .box-card {
    margin: 20px;
  }

  .sbox-card {
    margin: 20px;
  }

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 160px
  }

  .avatar-uploader :hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 160px;
    height: 160px;
    display: block;
    object-fit: cover; /* 裁剪图片保持比例，可选值：contain（缩放适应）、cover（裁剪填充） */
    border-radius: 4px; /* 圆角（可选） */
  }

  /* 仅对自定义按钮组内的按钮生效 */
  .spec-btn-group .el-button {
    background-color: white;
    color: #333;
    border-color: #dcdfe6;
    margin-right: 0px;
    /* 添加按钮间距 */
  }

  .spec-btn-group .el-button:last-child {
    margin-right: 0;
  }

  /* 选中状态样式（仅对该按钮组内的active-btn生效） */
  .spec-btn-group .active-btn {
    background-color: #409eff !important;
    color: white !important;
    border-color: #409eff !important;
  }

  .BtnDiv {
    margin-bottom: 30px;
  }

  .keyword-item {
    display: inline-block;
    background-color: #E8F4FF;
    border: 1px solid #D1E9FF;
    border-radius: 3px;
    padding: 0px 8px;
    margin-right: 5px;
    margin-top: 5px;
    line-height: 26px;
    cursor: pointer;
    color: #D49DFF;
  }

  .keyword-item i {
    margin-left: 5px;
    color: #D49DFF;
  }

  .keyword-item:hover i {
    color: #f56c6c;
  }

  .spec-image {
    max-width: 100%;
    max-height: 80px;
    object-fit: contain;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;
  }

  .editor-content {
    max-height: 600px;
    /* 设置最大高度 */
    overflow: auto;
    /* 超出部分显示滚动条 */
  }
 /* 原横向排列样式删除或注释 */
   .upload-preview {
     /* 改为块级元素布局（默认文档流） */
     display: block;
     margin-top: 10px;
   }

   /* 统一图片尺寸（纵向排列核心样式） */
   .upload-preview img {
     width: 160px; /* 固定宽度 */
     height: 160px; /* 固定高度 */
     object-fit: cover; /* 裁剪图片保持比例 */
     margin-bottom: 10px; /* 图片垂直间距 */
     border-radius: 4px;
   }
</style>
